#include "FileAppender.h"

namespace logging {

const int FileAppender::BUFFER_SIZE = LOG_BUFFER;

FileAppender::FileAppender(const char* name)
	: Appender(name) {

 	//Config::getValue(),
	_fd = open("log.txt",
		   O_WRONLY | O_APPEND | O_CREAT,
		   0000644);
	if ( _fd < 0 ) {
		_fd = dup(STDERR_FILENO);
	}

	//No thread safe, need to figure out how to manage buffer size at runtime
	//buffer_size = Config::getValue("logging.appender.buffer", (int)LOG_BUFFER_SIZE);
	//_buffer = malloc(buffer_size * sizeof(char));

}

FileAppender::~FileAppender() {
	close(_fd);
	//free(_buffer);
}

void FileAppender::write(Entry* entry) {

	char buffer[BUFFER_SIZE];

	time_t log_time = entry->getTimestamp();

	//Format the time
	char timestamp[26];	
	ctime_r(&log_time, timestamp);
	timestamp[24] = '\0';

	int len = snprintf(buffer, BUFFER_SIZE,
			   "%s - %s - %s\n", 
			   timestamp,
			   levelToString(entry->getLevel()),
			   entry->getMessage());

	if ( ::write(_fd, buffer, len) < len ) {
		//write error;
		syslog(LOG_ERR, "Logging Failure - [%s]\n", buffer);
	}
}

}
